package com.ts.login.controller;

import com.ts.login.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthBaiduRequest;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Controller
@RequestMapping("/login/baidu")
@Slf4j
public class BDAuthController {
    @Value("${auth.baidu.API-Key}")
    private String clientId;
    @Value("${auth.baidu.Secret-Key}")
    private String clientSecret;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private LoginService loginService;

    @Value("${server.port}")
    private String port;
    private String redirectUri = "/login/baidu/callback";

    @GetMapping
    public void renderAuth(HttpServletResponse response) throws IOException {
        log.info("用户选择百度认证");
        AuthRequest authRequest = getAuthRequest();
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/callback")
    public Object login(AuthCallback callback) {
        log.info("百度认证成功，code:{}", callback.getCode());
        AuthRequest authRequest = getAuthRequest();
        //根据code获取login
        AuthResponse login = authRequest.login(callback);
        //判断是否授权成功
        if (login.ok()) {
            //认证授权成功
            AuthUser _user = (AuthUser)login.getData();
            String token = loginService.loginByBaiDu(_user);
            String redirectUrl = String.format("redirect:http://localhost:8080?token=%s", token);
            return redirectUrl;
        } else {
            return "认证失败";
        }
    }

    private AuthRequest getAuthRequest() {
        String serverName = request.getServerName();
        String redirectUrl = "http://"+serverName + redirectUri;
        return new AuthBaiduRequest(AuthConfig.builder()
                .clientId(clientId)
                .clientSecret(clientSecret)
                .redirectUri("http://localhost:8200/login/baidu/callback")
                .build());
    }
}
